package edu.chinasoft.servlet;

import edu.chinasoft.domain.Dept;
import edu.chinasoft.domain.PageUnitForDept;
import edu.chinasoft.service.DeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author yljuan
 * @date 2020年1月19日:下午7:41:41
 * @version V1.0
 * @Description: 
 * 
*/
@WebServlet(name="myShowDeptServlet",value="/servlet/showdeptservlet")
public class  ShowDeptServlet  extends HttpServlet {
	private static Logger logger = LoggerFactory.getLogger(ShowDeptServlet.class);
	private DeptService deptService;
	
	/**
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.debug(" ShowDeptServlet >doGet start.......");
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		//获取分页单位
		ServletContext servletContext = this.getServletContext();
		String initParameter = servletContext.getInitParameter("pageUnit");
		int pageUnit = Integer.parseInt(initParameter);
		//获取当前页
		String pageParameter = request.getParameter("currentPage");
		pageParameter = pageParameter==null?"1":pageParameter;
		int currentPage = Integer.parseInt(pageParameter);
		int setLimit = (currentPage-1)*pageUnit;
		Map<String, Object> map = new HashMap<>();
		map.put("setLimit",setLimit);
		map.put("pageUnit",pageUnit);
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		DeptService deptServiceImp = wac.getBean("deptService", DeptService.class);
		this.deptService = deptServiceImp;
		PageUnitForDept pageUnitForDept = deptService.getRecordNum();
		List<Dept> deptList = deptService.selectUnitDept(map);
		pageUnitForDept.setDeptList(deptList);
		pageUnitForDept.setPageUnit(pageUnit);
		pageUnitForDept.setCurrentPage(currentPage);

		//加到session域里
		HttpSession session = request.getSession();
		session.setAttribute("deptPage", pageUnitForDept);
		
		response.sendRedirect(""+request.getContextPath()+"/showDept.jsp");
		
		logger.debug(" ShowDeptServlet >doGet end.......");
	}
	
	/**
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.debug(" ShowDeptServlet >doPost start.......");
		this.doGet(request, response);
		
		logger.debug(" ShowDeptServlet >doPost end.......");
	}
	
}